<template>
  <!-- 这是有tabs的 表格和表单 -->
  <div class="tabstable">
    <div v-if="loading" class="commonComponent_container_skeleton">
      <a-skeleton
        :width="60"
        active
        :paragraph="{
          rows: 5,
          width: '100%'
        }"
        :title="{
          width: '40%'
        }"
      />
    </div>
    <div v-if="emptyAppWarn" class="emptyApps">
      <div class="emptyApps-tip">
        抱歉， 组件走丢了
      </div>
    </div>
    <template v-if="Object.keys(parentHeaderData) && !emptyAppWarn">
      <template v-if="parentHeaderData.parentTableInfo && !parentHeaderData.parentTableInfo.accordingStyle">
        <div ref="tableTaps" class="table-taps">
          <el-tabs
            v-model="activeTab"
            @tab-click="tabsClick"
          >
            <el-tab-pane
              v-for="(item) in parentHeaderData.childrenTableInfos"
              :key="item.id"
              :label="item.tableName"
              :data="item"
            >
              <component
                :is="item.apps"
                ref="commonComponents"
                :active-tab="activeTab"
                :table-id="item.id"
                :table-type="item.tableType"
                :flag="flag"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
        <!-- <div class="commonComponent-body"> -->
        <!-- <keep-alive>
            <component
              :is="apps"
              ref="commonComponents"
              :table-id="tableId"
              :table-type="tableType"
              :flag="flag"
            />
          </keep-alive> -->
        <!-- </div> -->
      </template>
      <template v-else>
        <div class="commonComponentsRow">
          <div v-for="(item, index) in parentHeaderData.childrenTableInfos" :key="index">
            <div
              :style="colTableStyle(item)"
              class="commonComponentsRowTitle"
            >{{ item.tableName }}</div>
            <component
              :is="item.apps"
              ref="commonComponents"
              :table-id="item.id"
              :table-type="item.tableType"
              :flag="flag"
              :is-vertical-form="isVerticalForm"
              class="commonComponentsRowComp"
            />
          </div>
        </div>

      </template>
    </template>
  </div>
</template>

<script type="text/ecmascript-6">
/* eslint-disable no-labels */
/* eslint-disable no-unused-vars */
import {
  getHeaderByTableId,
  getParentHeader
} from '@/api/dynamicInterface';
import _ from 'lodash';
import { getSystemVariable } from '@/utils/utils';
import { TabsTableMixins } from './TabsTableMixins';

export default {
  mixins: [TabsTableMixins],
  props: {
    errorComponents: {
      type: Boolean,
      default: false
    },
    isProcess: {
      type: Number,
      default: 1
    },
    specilaMenuId: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      apps: '',
      emptyAppWarn: false,
      activeTab: '',
      menuId: '',
      formGuid: '',
      tableId: -1,
      parentHeaderData: {
        // childrenTableInfos  tableTaps
        // parentBodys  unknow
        // parentHeaders  .commonComponent-head 的数据
        // parentTableInfo  unknow
      },
      flag: '',

      form: {
        // headers // 公共headers
        // bodys  // 公共body
      },
      tableType: 0,
      loading: false,
      tableName: '',
      // 是否为竖向表单
      isVerticalForm: false
      // isFirstLoad: false
      // tabs: true,
    };
  },

  provide() {
    return {
      form: () => this.form
    };
  },
  computed: {
    colTableStyle() {
      return (item) => {
        return {
          'fontWeight': item.tabIsBold ? 'bold' : '500',
          'height': item.tabHeight ? item.tabHeight + 'px' : '40px',
          'lineHeight': item.tabHeight ? item.tabHeight + 'px' : '40px',
          'border-radius': item.borderRadius.split(':')[1] || item.borderRadius || 0,
          'fontSize': item.tabFontSize ? item.tabFontSize + 'px' : '18px',
          'color': item.tabFontColor ? item.tabFontColor : '#000',
          'backgroundColor': item.tabBackgroundColor ? item.tabBackgroundColor : '#1492ff'
        };
      };
    }
  },

  created() {
    const {
      formGuid,
      flag
    } = this.$route.query;
    this.flag = flag + '';
    this.menuId = this.isProcess === 1 ? this.$route.query.menuId : this.specilaMenuId;
    this.formGuid = formGuid;
    if (this.errorComponents) {
      this.emptyAppWarn = true;
    } else {
      this.initPage();
    }
  },
  methods: {
    getHeaderByTableId(styleHead, tabInfo) {
      const { tableId, tableName, tableType } = this;
      getHeaderByTableId({
        tableId,
        formGuid: this.formGuid
      }).then(res => {
        if (res.success) {
          res.data.headers.sort((a, b) => a.orderId - b.orderId);
          res.data.headers.forEach(item => {
            if (item.colspanCount >= 4) {
              item.myValue = item.title;
            } else {
              if (item.systemVariablesName) {
                item.myValue = getSystemVariable(item.systemVariablesName);
              } else {
                item.myValue = ''; // 存放数据（用于提交）
              }
            }
            item.opintion = []; // 下拉框存放选中的数据
            item.treeSelectItem = {}; // 下拉框存放选中的数据
            item.editMark = false; // 标记是否被编辑过
            item.selectViewOptions = item.selectViewOptions && Object.keys(item.selectViewOptions).length && item.selectViewOptions || {
              renderKey: 'lable',
              renderMapKey: 'value',
              renderValue: 'lable'
            };
          });
          this.form[tableId] = {
            ...res.data,
            tableName,
            tableType,
            styleHead,
            tableId
          };
          if (tabInfo && tabInfo.data) {
            this.form[tableId].tabInfo = tabInfo.data;
          }
          const formDatas = this.getFormValues();
          if (formDatas.length) {
            formDatas.forEach(item => {
              if (item) {
                const body = item.bodys && item.bodys[0];
                const header = item.headers;
                if (body) {
                  if (!header[-1]) {
                    header[-1] = 1;
                    for (const key in body) {
                      const headItem = header.find(item => item.dataIndex === key);
                      if (headItem) {
                        headItem.myValue = body[key];
                      }
                    }
                  }
                }
              }
            });
          }
        } else {
          this.form[tableId] = {};
          this.apps = '';
          this.$message.warning(res.message);
        }
        setTimeout(() => {
          this.getComponentsData();
        }, 300);
      });
    },
    // 获取表单表头(fu)
    getHeader({ menuId, formGuid }) {
      return getParentHeader({
        menuId, formGuid
      });
    },

    // tabClick({ $attrs: { data }}) {
    tabClick(obj) {
      this.parentHeaderData.parentTableInfo.accordingStyle && (this.isVerticalForm = true);
      // if (this.parentHeaderData.parentTableInfo.accordingStyle) {
      // 是否为第一次加载
      // if (!this.isFirstLoad) {
      this.loading = true;
      const positionApp = {
        0: resolve => require(['@/components/tableComponent/index.vue'], resolve), // 报表
        1: resolve => require(['@/components/CommonForm/index.vue'], resolve), // 表单
        2: resolve => require(['@/components/CommonTable/index.vue'], resolve) // 单子
      };
      const asyncFun = [];
      this.parentHeaderData.childrenTableInfos.forEach(async item => {
        if (item.tableType in positionApp) {
          item.apps = positionApp[item.tableType];
        } else {
          item.apps = positionApp[0];
        }
        const { fontColor, fontSize, headerColor, lineHeight, lineSelect, isBold, isAutoWidth } = item;
        item.styleHead = {
          fontColor,
          fontSize,
          headerColor,
          lineHeight,
          lineSelect,
          isBold,
          isAutoWidth
        };
        const tabInfoCopy = _.cloneDeep(item);
        item.tabInfo = tabInfoCopy;
        asyncFun.push(this.getHeaderByTableIdRow(item));
      });
      Promise.all(asyncFun).then(() => {
        const commonComponents = this.$refs.commonComponents;
        commonComponents.forEach(item => {
          item.initData && item.initData();
        });

        this.loading = false;
        // this.isFirstLoad = true;
        // 这个好像也不需要触发
        if (!this.parentHeaderData.parentTableInfo.accordingStyle) {
          this.tabsClick(obj);
        }
      });
      // }
    },

    tabsClick({ $attrs: { data }}) {
      // 感觉下面的事件都不需要触发
      this.apps = '';
      const { id: tableId, tableType, tableName } = data;
      // const { id: tableId, tableType, tableName, fontColor, fontSize, headerColor, lineHeight, lineSelect, isBold, isAutoWidth } = data;
      const positionApp = {
        0: resolve => require(['@/components/tableComponent/index.vue'], resolve), // 报表
        1: resolve => require(['@/components/CommonForm/index.vue'], resolve), // 表单
        2: resolve => require(['@/components/CommonTable/index.vue'], resolve) // 单子
      };
      this.tableId = tableId;
      this.tableType = tableType;
      this.tableName = tableName;
      this.tableButtons = data.buttons;
      if (tableType in positionApp) {
        // 动态加载组件
        this.apps = positionApp[tableType];
        if (this.form[tableId] && tableType) {
          setTimeout(() => {
            this.getComponentsData();
          }, 300);
        }
      } else {
        this.apps = positionApp[0];
      }
      /*       if (!this.form[tableId]) {
        const styleHead = {
          fontColor,
          fontSize,
          headerColor,
          lineHeight,
          lineSelect,
          isBold,
          isAutoWidth
        };
        this.loading = true;
        this.getHeaderByTableId(styleHead, { data });
      } */

      if (JSON.stringify(this.form[tableId]) === '{}') {
        this.apps = '';
        this.loading = false;
      }

      if (this.apps === '0') {
        this.emptyAppWarn = true;
      }
    },

    // 获取组件data
    async getComponentsData() {
      // 取数据
      const c = this.$refs.commonComponents;
      const ci = c[this.activeTab * 1];
      const initData = ci && ci.initData;
      // 刷新组件实例
      initData && await initData(); // 在组件内定义一个取数据的方法s
      this.loading = false;
    },

    getHeaderByTableIdRow(obj) {
      const { id, tableName, tableType, styleHead, tabInfo } = obj;
      return new Promise((resolve, reject) => {
        getHeaderByTableId({
          tableId: id,
          formGuid: this.formGuid
        }).then(res => {
          if (res.success) {
            res.data.headers.sort((a, b) => a.orderId - b.orderId);
            res.data.headers.forEach(item => {
              if (item.colspanCount >= 4) {
                item.myValue = item.title;
              } else {
                // item.myValue = ''; // 存放数据（用于提交）
                if (item.systemVariablesName) {
                  item.myValue = getSystemVariable(item.systemVariablesName);
                } else {
                  item.myValue = ''; // 存放数据（用于提交）
                }
              }
              item.opintion = []; // 下拉框存放选中的数据
              item.treeSelectItem = {}; // 下拉框存放选中的数据
              item.editMark = false; // 标记是否被编辑过
              item.selectViewOptions = item.selectViewOptions && Object.keys(item.selectViewOptions).length && item.selectViewOptions || {
                renderKey: 'lable',
                renderMapKey: 'value',
                renderValue: 'lable'
              };
            });
            this.form[id] = {
              ...res.data,
              tableName,
              tableType,
              styleHead,
              tableId: id,
              tabInfo
            };
            const formDatas = this.getFormValues();
            if (formDatas.length) {
              formDatas.forEach(item => {
                if (item) {
                  const body = item.bodys && item.bodys[0];
                  const header = item.headers;
                  if (body) {
                    if (!header[-1]) {
                      header[-1] = 1;
                      for (const key in body) {
                        const headItem = header.find(item => item.dataIndex === key);
                        if (headItem) {
                          headItem.myValue = body[key];
                        }
                      }
                    }
                  }
                }
              });
            }
            resolve();
          }
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.tabstable {
  width: 100%;
  padding: 20px;
  .commonComponent_container_skeleton{
    background-color: #fff;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 33;
    padding: 20px;
    padding-top: 60px;
    /deep/ .ant-skeleton-content .ant-skeleton-paragraph > li,
    /deep/ .ant-skeleton-content .ant-skeleton-title
    {
      height: 35px;
      border-radius: 8px;
    }
  }
  // .table-taps {
  //   margin-left: 44px;
  // }
  .commonComponent-body {
    width: 100%;
    height: calc(100% - 54px);
    overflow-y: auto;
    // padding:5px 15px;
  }

  .commonComponentsRow{
    overflow-y: auto;
    border-left: 1px solid #dddddd;
    border-right: 1px solid #dddddd;
    border-bottom: 1px solid #dddddd;
    //列表不要间距了
    // .commonComponentsRowComp{
    //   padding: 20px;
    // }
    .commonComponentsRowTitle{
      padding-left: 20px;
      border-top: 1px solid #ddd;
      border-bottom: 1px solid #ddd;
    }
    .commonComponentsRowTableName{
      height: 40px;
      background-color: #E1EFFC;
      line-height: 40px;
      font-size: 18px;
      font-weight: 600;
      padding-left: 4px;
      border-bottom: 1px solid #ccc;
      border-top: 1px solid #ccc;
      font-weight: bold;
    }
  }

  .emptyApps {
    width: 100%;
    height: 100%;
    background-image: url('~@/assets/images/monthReport/noReport.png');
    background-repeat: no-repeat;
    background-position: 50% 50%;
    display: flex;
    justify-content: center;
    .emptyApps-tip {
      position: relative;
      height: 30px;
      top: 70%;
      color: #E1E1E1;
    }
  }
  .table-taps{
    height: 100%;
    .el-tabs{
      height: 100%;
      /deep/.el-tabs__content{
        height: calc(100% - 70px);
        .el-tab-pane{
          height: 100%;
        }
      }
    }
  }
}

</style>
